/**
 * @FileName: LoginController.java
 * @Author
 * @Description:
 * @Date 2016年1月4日 上午11:39:53
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.h5;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.constant.H5ApiConstant;
import cn.hpclub.server.restful.API;
import cn.hpclub.server.util.InterfaceUtil;

@API("/tariffService")
public class TariffServiceController extends BaseH5Controller{
    private static final Logger logger             = LoggerFactory.getLogger(TariffServiceController.class);
    private static final int    TYPE_ZIFEI_HUODONG = 0;

    public void getTariffClassList(){
        getActivityListResponse(TYPE_ZIFEI_HUODONG, getPara("storeId"));
    }

    /**
     * @Title: getActivityListResponse
     * @Description:活动列表接口，根据act_type获取该分类的活动列表
     * @param typegetActivityList
     *            void
     */
    private void getActivityListResponse(int type, String orgId){
        try{
            List<Record> list = getActivityList(type, Integer.parseInt(orgId));
            JSONArray ja = getResponseJsonObject(list);
            JSONObject jo = new JSONObject();
            getActivityInfo(type, jo);

            jo.put("ResultCode", 1000);
            jo.put("Message", "成功");
            jo.put("data", ja);
            renderText(jo.toString());
        }
        catch(Exception e){
            e.printStackTrace();
            renderText(setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, "服务器异常:" + e.getMessage(), null).toString());
        }
    }

    /**
     * @Title: getActivityInfo
     * @Description:TODO
     * @param type
     * @param jo
     *            void
     */

    private void getActivityInfo(int type, JSONObject jo){
        Record record = Db.findFirst("SELECT title, description,icon_url FROM activity WHERE type=? and is_deleted=0",
                                     type);
        if(record != null){
            jo.put("title", record.getStr("title"));
            jo.put("description", record.getStr("description"));
            jo.put("icon_url", record.getStr("icon_url"));
        }
    }

    private void getTariffPackagesResponse(int type, String orgId){
        try{
            List<Record> list = getPackages(type, Integer.parseInt(orgId));
            JSONArray ja = getTariffPackagesArray(list);
            JSONObject jo = new JSONObject();
            jo.put("ResultCode", 1000);
            jo.put("Message", "成功");
            jo.put("data", ja);
            renderText(jo.toString());
        }
        catch(Exception e){
            e.printStackTrace();
            renderText(setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, "服务器异常:" + e.getMessage(), null).toString());
        }
    }

    public void getActivityList(){
        getActivityListResponse(getParaToInt("act_type"), getPara("storeId"));
    }

    /**
     * @Title: getTariffPackages
     * @Description:根据type获取对应资费大类下面的所有小类。为乡音网而写，但是通用。乡音网type传4.
     */
    public void getTariffPackages(){
        getTariffPackagesResponse(getParaToInt("act_type"), getPara("storeId"));
    }

    /**
     * @Title: getResponseJsonObject
     * @Description:TODO
     * @param list
     * @return JSONArray
     */

    private JSONArray getResponseJsonObject(List<Record> list){
        JSONArray ja = new JSONArray();
        JSONObject activity = null;
        JSONArray subList = null;
        long activityId = -1;
        for(int i = 0; i < list.size(); i++){
            Record item = list.get(i);
            if(item.getLong("id") != activityId){
                logger.debug("activityId=" + activityId + ",id=" + item.getLong("id"));
                activityId = item.getLong("id");
                activity = new JSONObject();
                activity.put("id", item.getLong("id"));
                activity.put("title", item.getStr("activity_name"));
                subList = new JSONArray();
                activity.put("list", subList);
                ja.put(activity);
            }
            if(item.getInt("tariff_class_id") != null){
                JSONObject jo = new JSONObject();
                jo.put("id", item.getInt("tariff_class_id"));
                jo.put("name", item.getStr("tariff_class_name"));
                jo.put("icon", item.getStr("tariff_class_icon_url"));
                jo.put("province_activity", item.getStr("province_activity"));
                subList.put(jo);
            }
        }
        return ja;
    }

    private JSONArray getTariffPackagesArray(List<Record> list){
        JSONArray ja = new JSONArray();
        JSONObject jo = null;
        for(int i = 0; i < list.size(); i++){
            Record item = list.get(i);
            jo = new JSONObject();
            jo.put("name", item.getStr("name"));
            jo.put("code", item.getStr("code"));
            ja.put(jo);
        }
        return ja;
    }

    private List<Record> getActivityList(int type, int orgId){
        int provinceOrgId = InterfaceUtil.getIdTop();
        String parentOrgIdSql = InterfaceUtil.getParentOrgIdSql(orgId, Constant.MAX_ORG_LEVEL);
        String sql = "SELECT ac.id AS id, ac. NAME AS activity_name, ac.sort AS activity_sort, ac.remark AS title, tariff_class_id, tariff_class_name, tariff_class_icon_url, tariff_class_sort,IF ( tariff_class_org_id =?, 'true', 'false' ) AS province_activity "
                + " FROM activity ac LEFT JOIN ("
                + " SELECT tariff_class.id AS tariff_class_id, tariff_class. NAME AS tariff_class_name, tariff_class.icon_url AS tariff_class_icon_url, tariff_class.sort AS tariff_class_sort, activity_id, tariff_class.org_id AS tariff_class_org_id"
                + " FROM activity_tariff_class_relation, tariff_class WHERE tariff_class.id = activity_tariff_class_relation.tariff_class_id AND tariff_class.enabled = 1 AND tariff_class.is_deleted = 0 ) AS tmp ON ac.id = tmp.activity_id"
                + " WHERE ac.type = ? AND ac.is_deleted=0 AND tariff_class_org_id IN " + parentOrgIdSql
                + " ORDER BY activity_sort ASC, id ASC, province_activity DESC, tariff_class_sort ASC";
        return Db.find(sql, provinceOrgId, type);
    }

    private List<Record> getPackages(int type, int orgId){
        String parentOrgIdSql = InterfaceUtil.getParentOrgIdSql(orgId, Constant.MAX_ORG_LEVEL);
        String sql = " select * from tariff_class_relation tr,tariff t where t.id = tr.tariff_id and t.is_deleted=0 and t.enabled=1 "
                + " and t.org_id in " + parentOrgIdSql
                + " and tr.tariff_class_id in (select tc.id from tariff_class tc where tc.is_deleted = 0 and tc.enabled=1 "
                + " and tc.org_id in " + parentOrgIdSql
                + " and tc.id in (select ar.tariff_class_id from  activity ac,activity_tariff_class_relation ar where ac.type = ? and ar.activity_id = ac.id and ac.is_deleted=0)) order by t.sort asc;";
        return Db.find(sql, type);
    }

    /**
     * @Title: getTariffClass
     * @Description:获取资费大类信息（该资费大类所属资费列表） void
     */
    public void getTariffClass(){
        try{
            List<Record> list = getTariffList();
            JSONObject root = generateResponse4TariffClass(list);
            logger.debug("root:" + root.toString());
            // logger.info("root:" + root.toString());
            renderText(root.toString());
        }
        catch(Exception e){
            e.printStackTrace();
            renderText(setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, "服务器异常:" + e.getMessage(), null).toString());
        }
    }

    public void getTariff(){
        try{
            JSONObject jo = new JSONObject();
            getActivityInfo(getParaToInt("act_type"), jo);
            Record record = getTariffById(getPara("tariff_id"));
            if(record == null){
                jo.put("ResultCode", 1001);
                jo.put("Message", "选择的套餐不存在，请联系管理员");
                jo.put("data", "");
            } else{
                jo.put("ResultCode", 1000);
                jo.put("Message", "成功");
                JSONObject data = new JSONObject();
                data.put("name", record.getStr("name"));
                data.put("type", record.getInt("type"));
                data.put("code", record.getStr("code"));
                data.put("detail", record.getStr("detail"));
                jo.put("data", data);
            }
            renderText(jo.toString());
        }
        catch(Exception e){
            e.printStackTrace();
            renderText(setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, "服务器异常:" + e.getMessage(), null).toString());
        }
    }

    public void getTariffByCode(){
        try{
            JSONObject jo = new JSONObject();
            getActivityInfo(getParaToInt("act_type"), jo);
            Record record = getTariifByCode(getPara("code"));
            if(record == null){
                jo.put("ResultCode", 1004);
                jo.put("Message", "选择的套餐不存在，请联系管理员");
                jo.put("data", "");
            } else{
                jo.put("ResultCode", 1000);
                jo.put("Message", "成功");
                JSONObject data = new JSONObject();
                data.put("name", record.getStr("name"));
                data.put("type", record.getInt("type"));
                data.put("code", record.getStr("code"));
                data.put("detail", record.getStr("detail"));
                jo.put("data", data);
            }
            renderText(jo.toString());
        }
        catch(Exception e){
            e.printStackTrace();
            renderText(setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, "服务器异常:" + e.getMessage(), null).toString());
        }
    }

    /**
     * @Title: getTitle
     * @Description:TODO
     * @param para
     *            void
     */

    private void getActivityTitle(String para){
        // TODO Auto-generated method stub

    }

    /**
     * @Title: generateResponse
     * @Description:TODO
     * @param list
     * @return JSONObject
     */

    private JSONObject generateResponse4TariffClass(List<Record> list){
        JSONObject root = new JSONObject();
        root.put("ResultCode", 1000);
        root.put("Message", "成功");
        JSONObject data = new JSONObject();
        JSONArray tariffList = new JSONArray();
        for(Record record : list){
            JSONObject item = new JSONObject();
            item.put("id", record.getInt("id"));
            item.put("name", record.getStr("name"));
            item.put("code", record.getStr("code"));
            item.put("detail", record.getStr("detail"));
            item.put("type", record.getInt("type"));
            item.put("province_tariff", record.getStr("province_tariff"));
            item.put("is_activity", record.getInt("is_activity"));
            item.put("activity_name", record.getStr("activity_name"));
            tariffList.put(item);
        }
        data.put("list", tariffList);
        root.put("data", data);
        return root;
    }

    /**
     * @Title: getTariffList
     * @Description:获取资费列表
     * @return List<Record>
     */
    private List<Record> getTariffList(){
        String id = getPara("id");
        String orgId = getPara("storeId");
        int provinceOrgId = InterfaceUtil.getIdTop();
        String parentOrgIdSql = InterfaceUtil.getParentOrgIdSql(Integer.parseInt(orgId), Constant.MAX_ORG_LEVEL);
        String sql = "SELECT t.id AS id, t.name AS name, code, detail, t.org_id, t.type, IF ( t.org_id ="
                + provinceOrgId + ", 'true', 'false' ) AS province_tariff, t.sort, t.is_activity, t.activity_name "
                + " FROM tariff t, tariff_class tc, tariff_class_relation tcr WHERE t.enabled = 1 AND t.start_date <= CURDATE() AND t.end_date >= CURDATE() AND t.is_deleted = 0 AND tcr.tariff_id = t.id AND tcr.tariff_class_id = tc.id and tc.id =? AND t.org_id IN "
                + parentOrgIdSql + " ORDER BY province_tariff DESC, t.sort ASC";
        List<Record> list = Db.find(sql, id);
        return list;
    }

    private Record getTariffById(String id){
        return Db.findFirst("SELECT name,type,code,detail FROM tariff WHERE id=?", id);
    }

    private Record getTariifByCode(String code){
        return Db.findFirst(
                            "SELECT name,type,code,detail FROM tariff WHERE code=? AND org_id=? AND is_deleted=0 AND enabled=1",
                            code, InterfaceUtil.getIdTop());
    }

    /**
     * @Title: verifyTariff
     * @Description:业务校验接口，检查业务是否存在，是否在有效期内 void
     */
    public void verifyTariff(){
        String id = getPara("tariff_id");
        String sql = "SELECT id, name, start_date, end_date FROM tariff WHERE id=? AND enabled=1 AND is_deleted=0";
        Record record = Db.findFirst(sql, id);
        JSONObject jo = new JSONObject();
        if(record == null){
            /* 活动不存在 */
            jo.put("ResultCode", H5ApiConstant.ResultCode.FAIL_CODE);
            jo.put("Message", "该业务不存在，请联系后台管理员");
            renderText(jo.toString());
            return;
        }
        Date startDate = record.getDate("start_date");
        Date endDate = record.getDate("end_date");
        if(isInExpiryDate(startDate, endDate)){
            /* 活动在有效期内 */
            jo.put("ResultCode", H5ApiConstant.ResultCode.SUCCESS_CODE);
            jo.put("Message", "sucess");
            renderText(jo.toString());
        } else{
            /* 不在有效期内 */
            jo.put("ResultCode", H5ApiConstant.ResultCode.FAIL_CODE);
            jo.put("Message", "不在办理有效期内，不能办理该业务！");
            renderText(jo.toString());
        }
    }

    /**
     * @Title: isInExpiryDate
     * @Description:是否在有效期内
     * @param startDate开始时间
     * @param endDate结束时间
     * @return boolean
     */
    private boolean isInExpiryDate(Date startDate, Date endDate){
        Calendar start = Calendar.getInstance();
        start.setTime(startDate);
        Calendar end = Calendar.getInstance();
        end.setTime(endDate);
        end.set(Calendar.HOUR, 23);
        end.set(Calendar.MINUTE, 59);
        end.set(Calendar.SECOND, 59);
        Calendar cur = Calendar.getInstance();
        cur.setTime(new Date());
        return start.compareTo(cur) <= 0 && end.compareTo(cur) >= 0;
    }
}
